<template>
<!-- 预约 -->
  <div class="makeAnAppointment" @click="bodyClose($event)">
    <div class="makeAn-content">
      <ztitleBorder title="患者信息">
        <div class="search-head">
          <div class="search" ref="searchArea" >
            <el-input placeholder="搜索患者"  v-model="info" @input="querySearch">
              <template #prepend >
                <el-icon><search /></el-icon>
                </template>
            </el-input>
            <div class="info-plan" v-if="isShowPlan" ref="infoPlan">
              <el-empty v-if="!personList.length" description="暂无数据" style="width:100%; height: 180px"></el-empty>
              <template v-else>
                <div v-for="item in personList" :key="item">
                  <searchItem @searchItem="handleItem" :showRegister="false" :searchData="item"></searchItem>
                </div>
              </template>
              
            </div>
          </div>
          <div class="btns" @click="handlebtn">
            <span>
              <el-icon><plus /></el-icon>
              </span>
          </div>
        </div>
        <div class="search-ctx">
          <!-- 展开 -->
          <div class="callapse">
            <div class="show-head" @click="handleShow">
              <span class="head-ctx">
                <component :is="showWidget(item.type)"  v-for="item in personAdd" :key="item.name" :struc="item"  />
              </span>
              <span class="icon-btn">
                <el-icon v-if="isShow"><arrow-right /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
              </span>
              
            </div>
            <div class="show-content" v-show="!isShow">
              <!-- 有多条数据展开时 -->
            </div>
          </div>
        </div>
      </ztitleBorder>

      <ztitleBorder title="预约信息">
        <component :is="showWidget(item.type)"  v-for="item in infoAdd" :key="item.name" :struc="item"  />
      </ztitleBorder>
      <ztitleBorder title="预约项目">
        <searchradio :echoCheckList="echoCheckList"  @checkListChange="checkListChange"></searchradio>
      </ztitleBorder>
    </div>
    <div class="makeAn-footer">
      <el-button class="btn-2" @click="cancel">取消</el-button>
      <el-button class="btn-1" @click="register">保存预约</el-button>
    </div>
  </div>
</template>

<script lang ="ts">
import { Search, Plus, ArrowDown, ArrowRight } from '@element-plus/icons-vue'
import { defineComponent, reactive, ref, onMounted, PropType, watchEffect, watch } from 'vue';
import ztitleBorder from "../../components/titleBorder/titleBorder.vue"
import searchradio from './components/searchradio.vue';

import useShowWidget from "../widget/usechoose"
import useConfgin from '../../hook/getconfig'
import searchItem, { SearchItemType } from "../searchinput/searchItem.vue"
import { debounce } from "../../utils/debounce"
import { setLocalStorage } from '../../utils/setLocaStroage'

import { getNowDate } from '../../utils/nowDate'
import { getCustomerInfoAPi } from '../../api/common'

import useRequet, { RespData } from "../../hook/network"
import { ElMessage } from 'element-plus'
import useUser from '../../hook/user';


const ID = 521 // 预约信息
const PSELECT = 522 // 预约客户选择
type PersonInfo = {
  historySickNum: string,
  name: string,
  mobileNum: string,
  id: number
}

interface MackanAppEditInfo {
  id: number,
  customerId: number,
  clinicType: string,
  subscribeType: string,
  subscribeTime: string,
  timeLength: number,
  consultantId: number,
  departmentId: number,
  doctorId: number,
  nurseId: number,
  remark: string,
  itemIdsShow: number[]

}
export default defineComponent({
  props: {
    personId: {
      type: [Number, String]
    },
    personName: {
      type: String,
    },
    makeanappInfo: {
      type: Object as PropType<MackanAppEditInfo>
    }
  },
  components: {
    ztitleBorder,
    searchradio,
    searchItem,

    Search,
    Plus,
    ArrowDown,
    ArrowRight
  },
  emits: ['reloadList', 'handlebtn', 'cancel'],
  setup(props, context) {
    // 获取账户id
    const user = useUser();
    const request = useRequet({ path: "" });
    const showWidget = useShowWidget;
    const infoTotal = useConfgin(ID)
    const infoAdd = infoTotal.groupDataAdd;
    
    const personSelect = useConfgin(PSELECT)
    const personAdd = personSelect.groupDataAdd
    const info = ref( props.personName || '')

    const personId = ref(props.personId || null)
    const paln = ref('')
    const personInfo: PersonInfo = reactive({
      historySickNum: '',
      name: '',
      mobileNum: '',
      id: null
    } as any)
    const personList = ref([] as any)
    const isShowPlan = ref(false)
    const checkList = ref([] as number[])

    const handlebtn = () => {
        context.emit('handlebtn')
      }
    const cancel = () => {
      context.emit('cancel')
		}

    const checkListChange = (val:any) => {
      checkList.value = val
    }
    

    const serachPerson = () => {

      request.sendRequest({
        address: 'customer/info/getCompanyCustomer',
        params: {
          value: info.value || ''
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          personList.value = resp.data.records
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }

    const debounceSearch = debounce(serachPerson, 500)
    const querySearch = () => {
      if(info.value) {
        isShowPlan.value = true
        debounceSearch()
      } else {
        isShowPlan.value = false
      }
      
    }

    const getSubCompanyCustomerList = (val: string) => {
      console.log(val)
      if(val) {
        request.sendRequest({
          address: 'customer/info/getCompanyCustomer',
          params: {
            value: val || ''
          },
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
            let result = resp.data && resp.data.records[0]
            personAdd.value && personAdd.value.forEach((item: any) => {
              item.value = result[item.name]
            })
            personInfo.id = result.id
            
            let doctor = {
              id: result.lastDoctorId,
              name: result.lastDoctorName
            }
            
            setLocalStorage('doctor', doctor)

            
            infoAdd.value.map(i => {
              if(i.name === 'doctorId') {
                i.value = result.lastDoctorId
              }
            })

          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "GET",
        })
      }
      
    }
    // 用于 修复预约回显id
    
    const getCustomerInfo = async(id: any) => {
      let res: any = await getCustomerInfoAPi({}, id);
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
      let result = res.data
      personAdd.value && personAdd.value.forEach((item: any) => {
              item.value = result[item.name]
            })
            personInfo.id = result.id
      let doctor = {
              id: result.lastDoctorId,
              name: result.lastDoctorName
            }
            
      setLocalStorage('doctor', doctor);
      infoAdd.value.map(i => {
          if(i.name === 'doctorId') {
            i.value = result.lastDoctorId
          }
        })
    }


    onMounted(() => {
      if(personId.value) {
        getCustomerInfo(personId.value)
        // getSubCompanyCustomerList(info.value)
      }
    })
    
    

    // 点击item 数据添加
    const handleItem = (data:any) => {


      infoAdd.value.map(i => {
        if(i.name === 'doctorId') {
          i.value = data.lastDoctorId
        }
      })
      
      personAdd.value.forEach((item: any) => {
        item.value = data[item.name]
      })
      info.value = data.name
      personInfo.id = data.id


      isShowPlan.value = false
    }

    const isShow = ref(false)
    const handleShow = () => {
      isShow.value = !isShow.value
    }
    
    
    const infoPlan = ref('')
    // 默认是添加
    const currentStatus = ref('ADD')
    const visitRecordID = ref()
    let echoCheckList = ref([] as number[])
    let mackanApp:any = props.makeanappInfo
    watchEffect(() => {
      
      infoAdd.value.forEach(i => {
        // if(i.name === 'doctorId') {
        //   i.value = user.id
        // }

        if(i.name === 'createTime') {
          i.value = getNowDate()
        }
      })
      
      if(mackanApp && Object.keys(mackanApp).length > 0) {
        if(mackanApp.clickType) {
          currentStatus.value = 'ADD'
        } else {
          currentStatus.value = 'EDIT'
        }
        
        visitRecordID.value = mackanApp.id

        // getSubCompanyCustomerList(mackanApp.customerName)
        echoCheckList.value = mackanApp.itemIdsShow
        personInfo.id = mackanApp.customerId
        checkList.value = mackanApp.itemIdsShow

        console.log(mackanApp)
        personAdd.value.forEach(i => {
          console.log(i)
          if(i.name == 'name') {
            i.value = mackanApp.customerName
          }
          if(i.name == 'mobileNum') {
            i.value = mackanApp.customerPhone
          }
          if(i.name == "historySickNum") {
            i.value = mackanApp.customerHistorySickNum
          }
        })

        infoAdd.value.forEach(i => {
          for(let v in mackanApp) {
            if(i.name === v) {
              i.value = mackanApp[i.name]
            }
          }
        })
      }

    })
    
    const register = () => {
      let result = {} as any
      infoAdd.value.forEach(item => {
        result[item.name] = item.value
      })
      result.customerId = personInfo.id
      result.itemIdsShow = checkList.value

      console.log(result)
      for(let i in result) {
        if(i == 'customerId' && !result[i]) {
            ElMessage.warning('请选择要预约的患者哦')
            return
          }
        if(i == 'clinicType' && !result[i]) {
          ElMessage.warning('就诊类型不能为空哦')
          return
        }
        if(i == 'subscribeType' && !result[i]) {
          ElMessage.warning('预约类型不能为空哦')
          return
        }
        if(i == 'subscribeTime' && !result[i]) {
          ElMessage.warning('预约时间不能为空哦')
          return
        }
        if(i == 'timeLength' && !result[i]) {
          ElMessage.warning('持续时间不能为空哦')
          return
        }
      }
      if(currentStatus.value === 'ADD') {
        console.log('ADD')
        request.sendRequest({
          address: 'customer/subscribe/createSubscribe',
          params: result,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            console.log(resp.data)
            ElMessage.success('保存成功')
            cancel()
            // 刷新列表
            context.emit('reloadList')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "POST",
        })
      }

      if(currentStatus.value === 'EDIT') {
        console.log('EDIT')
        result.id = visitRecordID.value
        request.sendRequest({
          address: 'customer/subscribe/updateSubscribe',
          params: result,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            console.log(resp.data)
            ElMessage.success('修改成功')
            cancel()
            // 刷新列表
            context.emit('reloadList')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "POST",
        })
      }

      
    }
    
    return {
      info,
      paln,
      personInfo,
      personList,
      personAdd,
      checkList,
      infoPlan,
      querySearch,

      handlebtn,
      cancel,

      isShowPlan,
      isShow,
      handleShow,
      handleItem,

      currentStatus,
      visitRecordID,
      register,
      checkListChange,
      serachPerson,
      echoCheckList,
      request,

      showWidget,
      infoTotal,
      infoAdd
    }
  },
  methods: {
    bodyClose(e: Event) {
      if(this.$refs.searchArea &&  !(this.$refs.searchArea as any).contains(e.target)) {
        this.isShowPlan = false
      }
    }
  }
})
</script>

<style lang = "scss" scoped>
.makeAnAppointment {
  height: 100%;
  .makeAn-content {
    padding: 10px 20px;
    box-sizing: border-box;
    width: 100%;
    height: calc(100% - 60px);
    overflow: auto;
    .search-head {
    display: flex;
    width: 100%;
    .search {
      width: 100%;
      position: relative;
      .info-plan {
        position: absolute;
        width: 100%;
        height: 200px;
        box-shadow: 0 0 3px 0 #e9e9e9;
        z-index: 99;
        background: white;
        margin-top: 10px;
        overflow-y: auto;
        font-size: $fontSize-1;
      }
    }
    
    .btns {
      width: 30px;
      line-height: 30px;
      height: 30px;
      background: #e6e3e3;
      text-align: center;
      margin-left: 20px;
      border-radius: $radius-1;
      box-sizing: border-box;
      cursor: pointer;
    }
    }
    .search-ctx {
      padding-top: 10px;
      padding-bottom: 10px;
      width: 100%;
      display: flex;
      font-size: $fontSize;
      & > span {
        display: inline-block;
        flex: 1;
      }

      .callapse {
        width: 100%;
        background: #f4f4f5;
        box-sizing: border-box;
        .show-head {
          display: flex;
          height: 35px;
          line-height: 35px;
          cursor: pointer;
          .head-ctx {
            flex: 1;
            display: flex;
            justify-content: space-around;
          }
          .icon-btn {
            width: 35px;
            height: 35px;
            text-align: center;
          }
        }
        
        .show-content {
          width: 100%;
          background: white;
          & > span {
            padding: 10px;
            display: inline-block;
          }
        }
      }
    }
  }
  .makeAn-footer {
    width: 100%;
    height: 60px;
    line-height: 60px;
    box-shadow: 0 0 3px rgba(0, 0, 0, .3);
    background-color: #fff;
    flex: 1;
    text-align: right;
    .btn-1 {
      margin-right: 40px;
    }
  }
}

.showPlan {
  display: block !important;
}
</style>